import sys
import re, os, commands
from perf_decorater import time_decorater

def dealwith_statistics(result):
    r = result.split('\n')
    stat_info = {}
    for info in r:
        if re.match('^$', info):continue
        if not re.search(':', info):continue
        if re.search('Status', info):continue
        if re.match('Statistics', info):continue
        if re.match('Warning', info):continue
        key , value = info.split(':')
        value = value.strip()
        if key.find('Queries per second') != -1:
            stat_info['qps'] = float(value)
        if key.find('Queries sent') != -1:
            stat_info['send'] = long(value)
        if key.find('Queries completed') != -1:
            stat_info['completed'] = value
        if key.find('Queries lost') != -1:
            stat_info['lost'] = value
        if key.find('Response codes') != -1:
            stat_info['response'] = value
        if key.find('Average packet size') != -1:
            stat_info['packetsize'] = value

    return stat_info

@time_decorater
def start_dnsperf(qp_file, server, port=53, **opts):
    if opts == None:
        opts = {}
        opts['long'] = 1
        opts['maxq'] = 100
    else:
        if 'long' not in opts:
            opts['long'] = 1
        if 'maxq' not in opts:
            opts['maxq'] = 100

    cmd = 'dnsperf -d %s -s %s -p %d -l %d -q %d' % (qp_file, server, port, opts['long'], opts['maxq'])
    if opts and 'tsig' in opts:
        cmd = cmd + ' -y %s' % opts['tsig']
    print 'local:', cmd
    ret, val = commands.getstatusoutput(cmd)
    if ret == 0:
        return dealwith_statistics(val)
    else:
        print 'ERROR:', ret, val
        sys.exit(1)
def thread_num_list(cpus, proper):
    if proper == "0":
        numlist = [i for i in range(1, cpus + 1) if i % 2 == 0]  
        numlist.insert(0, 1)
    else:
        numlist = proper.split(',') 
        numlist = [int(i) for i in numlist]

    return numlist

if __name__ == '__main__':
    opts = {}
    opts['server'] = '218.241.108.183'
    opts['port'] = 8898
    opts['long'] = 3
    opts['maxq'] = 20
    start_dnsperf(opts)
